<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Article;
use App\Http\Model\ArticleContent;
use App\Http\Model\Category;
use App\Http\Model\Logs;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Mockery\CountValidator\Exception;

class ArticleController extends Controller
{
    /**
     * 添加文章
     * @return $this|array
     */
    public function addArticle(){
        check_auth([2,5]);
        if($input=Input::all()){
            $article=new Article();
            $articleContent=new ArticleContent();
            DB::beginTransaction();
            try{
                if($articleID=$article->create(['user_id'=>Session::get('admin')['id'],'title'=>$input['title'],
                        'category_id'=>$input['category_id'],'cover'=>$input['cover'],'banner'=>$input['banner']])){
                    if($articleContent->create(['content'=>$input['content'],'article_id'=>$articleID->id])){
                        DB::commit();
                        $res=1;
                    }else{
                        $res=0;
                        throw new Exception;
                    }
                }else{
                    $res=0;
                    throw new Exception;
                }
            }catch(Exception $e){
                DB::rollBack();
            }
            Logs::create(['username'=>Session::get('admin')['username'],'event'=>'-添加了文章'.$input['title']]);
            return $res?['status'=>1,'msg'=>'保存完成']:['status'=>0,'msg'=>'保存失败'];
        }
        $category=Category::where(['type'=>1,'status'=>1])->get()->all();
        return view('admin.article.add',compact('category'))->with(['title'=>'添加文章']);
    }

    /**
     * 文章列表包括回收站
     * @param $status 状态 1：列表，0：回收站
     * @return $this
     */
    public function articleList($status){
        check_auth([2,5]);
        $user_id=Session::get('admin')['id'];
        $endTime=$startTime=$titler=$category_id='';
        $allarticle=Article::select(
            'article.id','article.cover','article.title','article.banner','user.username','article.views',
            'article.status','category.category','article.created_at','article.updated_at'
        )->join('category','category.id','=','article.category_id','left')->orderBy('article.id','desc');
        if(!empty(Session::get('admin')['is_author'])){
            $allarticle=$allarticle->join('user','user.id','=','article.user_id','left')
                ->where(['article.status'=>$status,'user_id'=>$user_id]);
        }elseif(empty(Session::get('admin')['is_author'])){
            $allarticle=$allarticle->join('user','user.id','=','article.user_id','left')->where(['article.status'=>$status]);
        }
        if($search=Input::except('page')){
            $startTime=$search['start_time'];
            $endTime=$search['end_time'];
            $titler=$search['title'];
            $category_id=$search['category_id'];
            if(!empty($category_id)){
                $allarticle=$allarticle->where('category_id','=',$category_id);
            }
            if(!empty($titler)){
                $allarticle=$allarticle->where('article.title','like',"%".$titler."%");
            }
            if(!empty($startTime)){
                $allarticle=$allarticle->where('article.created_at','>',strtotime($startTime));
            }
            if(!empty($endTime)){
                $endTimer=strtotime($endTime)+3600*24;
                $allarticle=$allarticle->where('article.created_at','<',$endTimer);
            }
            $allarticle=$allarticle->paginate(7)->appends(['title' => $titler,'start_time'=>$startTime,'end_time'
            =>$endTime,'category_id'=>$category_id]);
        }else{
            $allarticle=$allarticle->paginate(7);
        }
        $category=Category::where(['type'=>1])->get()->all();
        return $status ? view('admin.article.list',compact('allarticle','titler','category_id','startTime','endTime','category'))
            ->with(['title'=>'文章列表']) :
            view('admin.article.recyclebin',compact('allarticle','titler','category_id','startTime','endTime',
                'category_id','category'))->with(['title'=>'文章回收站']);
    }

    /**
     * 更改文章状加入回收站
     * @return array
     */
    public function updateArticleStatus(){
        check_auth([2,5]);
        if($input=Input::all()){
            $status=$input['status']?0:1;
            if(Article::where(['id'=>$input['id']])->update(['status'=>$status])){
                Logs::create(['username'=>Session::get('admin')['username'],'event'=>'-修改了文章'.$input['id'].'状态'.$input['status']]);
                return ['status'=>1,'msg'=>'修改完成'];
            }else{
                return ['status'=>0,'msg'=>'修改失败'];
            }
        }
    }

    /**
     * 单个删除文章
     * @return array
     */
    public function deleteArticle(){
        check_auth([2,5]);
        if($input=Input::all()){
            return $this->delete($id=$input['id']);
        }
    }

    /**
     * 删除文章
     * @param $id 文章id
     * @return array
     */
    private function delete($id){
        $msg=$id.':';
        Logs::create(['username'=>Session::get('admin')['username'],'event'=>'-删除了文章'.$id]);
        $images=Article::select('cover','banner')->find($id);
        if(Article::where(['id'=>$id])->delete() && ArticleContent::where('article_id',$id)->delete()){
            $msg.='文章已删除,';
            $status=1;
            $disk = Storage::disk('qiniu');
            if(!empty($images->cover)){
                $cover=basename($images->cover);
                if($disk->exists($cover)){
                    if($disk->delete($cover)){
                        $msg.="封面图已经删除,";
                    }else{
                        $msg.="封面未删除,";
                    }
                }else{
                    $msg.="封面不存在,";
                }
            }
            if(!empty($images->banner)){
                $banner=basename($images->banner);
                if($disk->exists($banner)){
                    if($disk->delete($banner)){
                        $msg.="Banner图已经删除,";
                    }else{
                        $msg.="Banner图未删除,";
                    }
                }else{
                    $msg.="Banner图不存在,";
                }
            }
        }else{
            $status=0;
            $msg.='文章未删除';
        }
        return ['status'=>$status,'msg'=>$msg];
    }

    /**
     * 批量删除文章
     * @return array
     */
    public function multiDeleteArticle(){
        check_auth([2,5]);
        if($selected=Input::all()){
            $success='';
            $false='';
            foreach($selected['selected'] as $id){
                $res=$this->delete($id);
                if($res['status']){
                    $success.=$id.',';
                }else{
                    $false.=$id.',';
                }
            }
            return empty($false)?['status'=>1,'msg'=>$success.'已操作完成']:['status'=>1,'msg'=>$success.'操作完成,'.$false.'操作失败'];
        }
    }

    /**
     * 批量更改文章状态
     * @return array
     */
    public function multiUpdateArticleStatus(){
        check_auth([2,5]);
        if($selected=Input::all()){
            $success='';
            $false='';
            foreach($selected['selected'] as $id){
                if(Article::where(['id'=>$id])->update(['status'=>$selected['status']])){
                    Logs::create(['username'=>Session::get('admin')['username'],'event'=>'-更改了文章'.$id.'->'.$selected['status']]);
                    $success.=$id.',';
                }else{
                    $false.=$id.',';
                }
            }
            return empty($false)?['status'=>1,'msg'=>$success.'已操作完成']:['status'=>1,'msg'=>$success.'操作完成,'.$false.'操作失败'];
        }
    }

    /**
     * 修改文章 页面
     * @param $id 文章id
     * @return $this
     */
    public function editArticle($id){
        check_auth([2,5]);
        $articleInfo=Article::find($id);
        $articleContent=ArticleContent::select('content')->where('article_id',$id)->get()->all()[0];
        $category=Category::where(['type'=>1])->get()->all();
        return view('admin.article.edit',compact('category','articleContent','articleInfo'))->with(['title'=>'修改文章']);
    }

    /**
     * 更新文章
     * @return array
     */
    public function updateArticle(){
        check_auth([2,5]);
        if($input=Input::except('_token')){
            $id=$input['id'];
            $oldArticle=Article::find($id);
            $disk = Storage::disk('qiniu');
            if($oldArticle['cover']!=$input['cover']){
                //图片更新了，删除旧图
                if(!empty($oldArticle['cover'])){
                    $oldCover=basename($oldArticle->cover);
                    if($disk->exists($oldCover)){
                        $disk->delete($oldCover);
                    }
                }
            }
            if($oldArticle['banner']!=$input['banner']){
                //图片更新了，删除旧图
                if(!empty($oldArticle['banner'])){
                    $oldBanner=basename($oldArticle->banner);
                    if($disk->exists($oldBanner)){
                        $disk->delete($oldBanner);
                    }
                }
            }
            $content=$input['content'];
            unset($input['id']);
            unset($input['content']);
            if(ArticleContent::where(['article_id'=>$id])->update(['content'=>$content])
                && Article::where(['id'=>$id])->update($input)){
                Logs::create(['username'=>Session::get('admin')['username'],'event'=>'-更新了文章'.$input['title']]);
                return ['status'=>1,'msg'=>'更新完毕'];
            }else{
                return ['status'=>0,'msg'=>'更新失败'];
            }
        }
    }
}
